<template>
  <div class="contract-order-add-view">
    <div class="page-header">
      <h2>新增合同生成订单</h2>
    </div>

    <el-card class="form-card">
      <el-form 
        ref="contractForm" 
        :model="contractForm" 
        :rules="contractRules" 
        label-width="120px"
        v-loading="submitLoading"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户企业" prop="customer_id">
              <el-autocomplete
                v-model="companyName"
                :fetch-suggestions="searchCustomers"
                placeholder="请输入企业名称进行搜索"
                style="width: 100%;"
                @select="handleCustomerSelect"
                clearable
                :trigger-on-focus="false"
                :debounce="500"
                popper-class="customer-search-dropdown"

              >
                <template slot-scope="{ item }">
                  <div class="customer-option">
                    <div class="company-name">{{ item.customer.Name }}</div>
                    <div class="customer-info">
                      <span v-if="item.customer.UserName">负责人: {{ item.customer.UserName }}</span>
                      <span v-if="item.customer.Address">地址: {{ item.customer.Address }}</span>
                      <span v-if="item.customer.Tel">电话: {{ item.customer.Tel }}</span>
                    </div>
                  </div>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同编号" prop="contract_name">
              <el-input 
                v-model="contractForm.contract_name" 
                placeholder=""
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同金额" prop="cost">
              <el-input 
                v-model="contractForm.cost" 
                placeholder="请输入合同金额"
                type="number"
                step="0.01"
                class="amount-input"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款状态" prop="payment_status">
              <el-select v-model="contractForm.payment_status" placeholder="请选择付款状态" style="width: 100%;">
                <el-option label="未付款" :value="0"></el-option>
                <el-option label="已付款" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="12">
            <el-form-item label="是否需要施工" prop="is_construction">
              <el-select v-model="contractForm.is_construction" placeholder="请选择是否需要施工" style="width: 100%;">
                <el-option label="不施工" :value="0"></el-option>
                <el-option label="施工" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款时间" prop="payment_time" v-if="contractForm.payment_status === 1">
              <el-date-picker
                v-model="contractForm.payment_time"
                type="datetime"
                placeholder="请选择付款时间"
                style="width: 100%;"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="预计付款时间" prop="estimated_payment_time" v-if="contractForm.payment_status === 0">
              <el-date-picker
                v-model="contractForm.estimated_payment_time"
                type="datetime"
                placeholder="请选择预计付款时间"
                style="width: 100%;"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同图片" prop="img">
              <el-upload
                ref="upload"
                :action="uploadAction"
                :auto-upload="false"
                :on-change="handleFileChange"
                :on-remove="handleFileRemove"
                :file-list="fileList"
                :limit="5"
                accept="image/*"
                list-type="picture-card"
                :before-upload="() => false"
                multiple
              >
                <i class="el-icon-plus"></i>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过100MB，最多可上传5张图片</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款凭证" prop="img_payment">
              <el-upload
                ref="paymentUpload"
                :action="uploadAction"
                :auto-upload="false"
                :on-change="handlePaymentFileChange"
                :on-remove="handlePaymentFileRemove"
                :file-list="paymentFileList"
                :limit="5"
                accept="image/*"
                list-type="picture-card"
                :before-upload="() => false"
                multiple
              >
                <i class="el-icon-plus"></i>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过100MB，最多可上传5张图片</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同备注" prop="remark">
              <el-input 
                v-model="contractForm.remark" 
                type="textarea" 
                :rows="4"
                placeholder="请输入合同备注"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 收货人信息区域 -->
        <div class="recipient-info-section">
          <div class="recipient-header" @click="toggleRecipientInfo">
            <span class="recipient-title">收货人信息</span>
            <span class="recipient-toggle">【{{ showRecipientInfo ? '点击隐藏' : '点击显示' }}】</span>
          </div>
          
          <div v-if="showRecipientInfo" class="recipient-content">
            <p class="recipient-instruction">收货人信息已自动填写，如需修改请点击下方按钮</p>
            <el-button 
              type="primary" 
              size="small" 
              @click="editRecipientInfo"
              class="recipient-edit-btn"
            >
              点击按钮即可编辑收货人信息
            </el-button>
            
            <el-row :gutter="20" class="recipient-fields">
              <el-col :span="8">
                <el-form-item label="收货人" prop="recipient_name">
                  <el-input 
                    v-model="contractForm.recipient_name" 
                    placeholder="收货人姓名"
                    :disabled="!isEditingRecipient"
                    @input="handleRecipientChange"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系电话" prop="recipient_tel">
                  <el-input 
                    v-model="contractForm.recipient_tel" 
                    placeholder="联系电话"
                    :disabled="!isEditingRecipient"
                    @input="handleRecipientChange"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="收货地址" prop="recipient_address">
                  <el-input 
                    v-model="contractForm.recipient_address" 
                    placeholder="收货地址"
                    :disabled="!isEditingRecipient"
                    @input="handleRecipientChange"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <!-- 同步选项 -->
            <div v-if="isEditingRecipient && cartItems.length > 0" class="sync-option">
              <el-checkbox v-model="syncToAllProducts">
                同步更新所有已选产品的发货信息
              </el-checkbox>
              <el-button 
                v-if="syncToAllProducts" 
                type="text" 
                size="mini" 
                @click="applyRecipientToAll"
                style="margin-left: 10px; color: #409eff;"
              >
                立即应用
              </el-button>
            </div>
          </div>
        </div>
        
        <!-- 产品选择区域 -->
        <div class="product-selection-section">
          <div class="product-header" @click="toggleProductSelection">
            <span class="product-title">产品选择</span>
            <span class="product-toggle">【{{ showProductSelection ? '点击隐藏' : '点击显示' }}】</span>
          </div>
          
          <div v-if="showProductSelection" class="product-content">
            <p class="product-instruction">请选择要生成订单的产品和配件</p>
            
            <!-- 产品搜索框 -->
            <div class="product-search">
              <el-input
                v-model="productSearchKeyword"
                placeholder="请输入产品名称进行搜索"
                prefix-icon="el-icon-search"
                size="small"
                style="width: 300px;"
                clearable
                @input="filterProducts"
              ></el-input>
            </div>
            
            <!-- 设备列表 -->
            <div class="device-list">
              <h4>设备列表</h4>
              
              <div v-for="device in filteredDeviceList" :key="device.id" class="device-item">
                <div class="device-header">
                  <div class="device-title">
                    <strong>{{ device.device_name }}</strong>
                    <el-tag v-if="device.is_need" type="warning" size="mini">需要流量卡</el-tag>
                    <el-tag v-else type="info" size="mini">无需流量卡</el-tag>
                  </div>
                  <div class="device-actions">
                    <div class="quantity-selector">
                      <label>数量：</label>
                      <el-input-number 
                        v-model="device.quantity" 
                        :min="1" 
                        :max="9999"
                        size="mini"
                        style="width: 100px;"
                        placeholder="数量"
                        @change="handleDeviceQuantityChange(device)"
                      ></el-input-number>
                    </div>
                    <el-button 
                      type="primary" 
                      size="mini" 
                      @click="addDeviceToCart(device)"
                      icon="el-icon-plus"
                    >
                      添加产品
                    </el-button>
                  </div>
                </div>
                
                <div class="factory-info">
                  <span><strong>工厂：</strong>{{ device.factory.factory_name }}</span>
                  <span><strong>地址：</strong>{{ device.factory.address }}</span>
                </div>
                
                <!-- 配件列表 -->
                <div class="accessories-list">
                  <h5>配件列表：</h5>
                  <div class="accessories-grid">
                    <div 
                      v-for="accessory in device.accessories" 
                      :key="accessory.id"
                      class="accessory-item"
                    >
                      <div class="accessory-header">
                        <el-checkbox 
                          v-model="accessory.selected" 
                          @change="handleAccessoryChange(device, accessory)"
                        >
                          <span class="accessory-name">{{ accessory.accessory_name }}</span>
                        </el-checkbox>
                        <el-tag 
                          :type="accessory.is_standard === 1 ? 'success' : 'warning'" 
                          size="mini"
                        >
                          {{ accessory.is_standard === 1 ? '标配' : '选配' }}
                        </el-tag>
                      </div>
                      
                      <!-- 规格选择 -->
                      <div v-if="accessory.selected && accessory.skus && accessory.skus.length > 0" class="sku-selection">
                        <div class="form-item">
                          <label class="form-label">规格：</label>
                          <el-select 
                            v-model="accessory.selectedSkuId" 
                            placeholder="请选择规格"
                            size="small"
                            style="width: 200px;"
                          >
                            <el-option 
                              v-for="sku in accessory.skus" 
                              :key="sku.id"
                              :label="sku.value" 
                              :value="sku.id"
                            ></el-option>
                          </el-select>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 已选产品列表 -->
            <div class="selected-products">
              <h4>已选产品 
                <el-button type="text" size="mini" @click="clearCart" style="margin-left: 10px;">清空已选择产品</el-button>
                <el-button 
                  v-if="cartItems.length > 0" 
                  type="text" 
                  size="mini" 
                  @click="syncShippingInfo" 
                  style="margin-left: 10px; color: #409eff;"
                  icon="el-icon-refresh"
                >
                  同步发货信息
                </el-button>
              </h4>
              <div v-if="cartItems.length === 0" class="empty-cart">
                <p style="color: #999; text-align: center; padding: 20px;">未选择任何产品，请选择产品</p>
              </div>
              <div v-else class="cart-items">
                <div v-for="(item, index) in cartItems" :key="index" class="cart-item">
                  <div class="cart-item-header">
                    <div class="device-info">
                      <span class="device-name">{{ item.device_name }}</span>
                      <span v-if="item.accessories && item.accessories.length > 0" class="device-config">
                        ({{ item.accessories.map(acc => {
                          if (acc.sku_value && acc.sku_value.trim()) {
                            return acc.accessory_name + ' - ' + acc.sku_value;
                          } else {
                            return acc.accessory_name;
                          }
                        }).join(', ') }})
                      </span>
                    </div>
                    <el-button 
                      type="danger" 
                      size="mini" 
                      @click="removeFromCart(index)"
                      icon="el-icon-delete"
                    >
                      删除
                    </el-button>
                  </div>
                  
                  <div class="cart-item-details">
                    <div class="quantity-section">
                      <label>数量：</label>
                      <el-input-number 
                        v-model="item.quantity" 
                        :min="1" 
                        :max="9999"
                        size="mini"
                        style="width: 100px;"
                      ></el-input-number>
                    </div>
                    
                    <div class="accessories-section" v-if="item.accessories && item.accessories.length > 0">
                      <label>配件：</label>
                      <div class="accessories-tags">
                        <el-tag 
                          v-for="accessory in item.accessories" 
                          :key="accessory.id"
                          size="mini"
                          :type="accessory.is_standard === 1 ? 'success' : 'warning'"
                        >
                          {{ accessory.accessory_name }}{{ accessory.sku_value ? ' - ' + accessory.sku_value : '' }}
                          <span style="font-size: 10px; margin-left: 4px;">({{ accessory.is_standard === 1 ? '标配' : '选配' }})</span>
                        </el-tag>
                      </div>
                    </div>
                    
                    <!-- 发货信息区域 -->
                    <div class="shipping-info-section">
                      <h5 class="shipping-title">
                        <i class="el-icon-location"></i>
                        发货信息
                      </h5>
                      <div class="shipping-form">
                        <el-row :gutter="15">
                          <el-col :span="8">
                            <div class="form-item">
                              <label class="form-label">收货人：</label>
                              <el-input 
                                v-model="item.shipping_info.recipient_name" 
                                placeholder="收货人姓名"
                                size="small"
                                clearable
                              ></el-input>
                            </div>
                          </el-col>
                          <el-col :span="8">
                            <div class="form-item">
                              <label class="form-label">联系电话：</label>
                              <el-input 
                                v-model="item.shipping_info.recipient_tel" 
                                placeholder="联系电话"
                                size="small"
                                clearable
                              ></el-input>
                            </div>
                          </el-col>
                          <el-col :span="8">
                            <div class="form-item">
                              <label class="form-label">收货地址：</label>
                              <el-input 
                                v-model="item.shipping_info.recipient_address" 
                                placeholder="收货地址"
                                size="small"
                                clearable
                              ></el-input>
                            </div>
                          </el-col>
                        </el-row>
                        <el-row :gutter="15" style="margin-top: 10px;">
                          <el-col :span="24">
                            <div class="form-item">
                              <label class="form-label">订单备注：</label>
                              <el-input 
                                v-model="item.shipping_info.remark" 
                                placeholder="请输入该产品的订单备注信息"
                                type="textarea"
                                :rows="2"
                                size="small"
                                clearable
                              ></el-input>
                            </div>
                          </el-col>
                        </el-row>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <el-form-item>
          <br>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">提交合同并生成订单</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getContractNumber, searchCustomerByCompany, getDeviceListMore } from '@/api/contract';
import { checkToken, handleTokenExpired, checkTokenFromError } from '@/utils/auth';
import request from '@/utils/request';

export default {
  name: 'ContractOrderAdd',
  data() {
    return {
      // 表单数据
      contractForm: {
        customer_id: '',
        contract_name: '',
        remark: '',
        payment_time: '',
        payment_status: 1,
        cost: '',
        is_construction: 0,
        estimated_payment_time: '',
        // 收货人信息字段
        recipient_name: '',
        recipient_tel: '',
        recipient_address: ''
      },
      
      // 客户搜索相关
      companyName: '',
      
      // 收货人信息显示控制
      showRecipientInfo: false,
      isEditingRecipient: false,
      syncToAllProducts: false, // 新增同步选项
      
      // 表单验证规则
      contractRules: {
        customer_id: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
        contract_name: [
          { required: true, message: '请输入合同名称', trigger: 'blur' }
        ],
        cost: [
          { required: true, message: '请输入合同金额', trigger: 'blur' }
        ],
        payment_status: [
          { required: true, message: '请选择付款状态', trigger: 'change' }
        ],
        is_construction: [
          { required: true, message: '请选择是否需要施工', trigger: 'change' }
        ]
      },
      
      // 文件上传相关
      fileList: [],
      paymentFileList: [],
      uploadAction: '#', // 不使用自动上传
      
      // 图片路径数组
      imgUrls: [], // 合同图片路径数组
      paymentImgUrls: [], // 付款凭证图片路径数组
      
      // 提交状态
      submitLoading: false,
      
      // 产品选择相关
      showProductSelection: false,
      deviceList: [],
      cartItems: [],
      productSearchKeyword: '', // 新增产品搜索关键词
      filteredDeviceList: [] // 新增过滤后的设备列表
    }
  },
  mounted(){
    this.getContractNumber();
    this.loadDeviceList();
  },
  methods: {
    // 获取合同编号
    async getContractNumber() {
      try {
        const response = await getContractNumber();
        if (response.data && response.data.msg) {
          this.contractForm.contract_name = response.data.msg;
        }
      } catch (error) {
        console.error('获取合同编号失败:', error);
      }
    },
    
    // 加载设备列表
    async loadDeviceList() {
      try {
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }
        
        const response = await getDeviceListMore();
        
        if (response.data && response.data.code === true) {
          // 处理设备数据，为配件添加选择状态和默认规格选择
          this.deviceList = response.data.data.map(device => ({
            ...device,
            quantity: 1, // 默认数量为1
            accessories: device.accessories.map(accessory => {
              const accessoryData = {
                ...accessory,
                selected: accessory.is_standard === 1, // 标配默认选中，选配默认不选中
                selectedSkuId: null // 初始化为null
              };
              
              // 如果有规格，设置默认选择第一个
              if (accessory.skus && accessory.skus.length > 0) {
                accessoryData.selectedSkuId = accessory.skus[0].id;
              }
              
              return accessoryData;
            })
          }));
          this.filteredDeviceList = this.deviceList; // 初始化过滤后的列表
          console.log('设备列表数据:', this.deviceList);
        } else {
          this.$message.error(response.data.msg || '获取设备列表失败');
        }
      } catch (error) {
        console.error('获取设备列表失败:', error);
        if (checkTokenFromError(error)) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          this.$message.error('获取设备列表失败');
        }
      }
    },
    
    // 切换产品选择显示/隐藏
    toggleProductSelection() {
      this.showProductSelection = !this.showProductSelection;
    },
    
    // 添加设备
    addDeviceToCart(device) {
      // 收集选中的配件（标配和手动选中的选配）
      const selectedAccessories = [];
      device.accessories.forEach(accessory => {
        if (accessory.selected) {
          const accessoryItem = {
            id: accessory.id,
            accessory_name: accessory.accessory_name,
            is_standard: accessory.is_standard,
            sku_id: accessory.selectedSkuId,
            sku_value: accessory.selectedSkuId ? accessory.skus.find(sku => sku.id === accessory.selectedSkuId)?.value : null
          };
          selectedAccessories.push(accessoryItem);
        }
      });
      
      // 生成唯一的项目标识（设备ID + 配件组合的哈希值）
      const accessoriesHash = this.generateAccessoriesHash(selectedAccessories);
      const cartItemKey = `${device.id}_${accessoriesHash}`;
      
      // 检查是否已存在相同配置的设备
      const existingCartItem = this.cartItems.find(item => {
        const itemAccessoriesHash = this.generateAccessoriesHash(item.accessories);
        return item.device_id === device.id && itemAccessoriesHash === accessoriesHash;
      });
      
      if (existingCartItem) {
        // 如果配置已存在，更新数量
        existingCartItem.quantity = device.quantity;
        this.$message.success(`已更新 ${device.device_name} 的数量`);
      } else {
        // 如果配置不存在，创建新的项目
        const cartItem = {
          id: cartItemKey, // 添加唯一标识
          device_id: device.id,
          device_name: device.device_name,
          factory: device.factory,
          is_need: device.is_need,
          quantity: device.quantity,
          accessories: selectedAccessories,
          shipping_info: { // 新增发货信息对象，默认填充当前客户信息
            recipient_name: this.contractForm.recipient_name || '',
            recipient_tel: this.contractForm.recipient_tel || '',
            recipient_address: this.contractForm.recipient_address || '',
            remark: ''
          }
        };
        
        this.cartItems.push(cartItem);
        this.$message.success(`已添加 ${device.device_name} `);
      }
    },
    
    // 移除项目
    removeFromCart(index) {
      this.cartItems.splice(index, 1);
      this.$message.success('已移除');
    },
    
    // 清空
    clearCart() {
      this.cartItems = [];
    },
    
    // 处理配件选择变化
    handleAccessoryChange(device, accessory) {
      if (accessory.selected) {
        // 如果配件有规格，确保选择了规格
        if (accessory.skus && accessory.skus.length > 0 && !accessory.selectedSkuId) {
          this.$set(accessory, 'selectedSkuId', accessory.skus[0].id);
        }
      } else {
        // 如果取消选择配件，清空规格选择
        this.$set(accessory, 'selectedSkuId', null);
      }
    },
    
    // 处理设备数量变化，同步购物车中的数量
    handleDeviceQuantityChange(device) {
      // 收集当前选中的配件
      const selectedAccessories = [];
      device.accessories.forEach(accessory => {
        if (accessory.selected) {
          const accessoryItem = {
            id: accessory.id,
            sku_id: accessory.selectedSkuId || 'no_sku'
          };
          selectedAccessories.push(accessoryItem);
        }
      });
      
      // 生成当前配置的哈希值
      const currentHash = this.generateAccessoriesHash(selectedAccessories);
      
      // 查找对应配置的商品并更新数量
      const cartItem = this.cartItems.find(item => {
        const itemHash = this.generateAccessoriesHash(item.accessories);
        return item.device_id === device.id && itemHash === currentHash;
      });
      
      if (cartItem) {
        cartItem.quantity = device.quantity;
      }
    },
    
    // 生成配件组合的哈希值，用于区分不同配置
    generateAccessoriesHash(accessories) {
      if (!accessories || accessories.length === 0) {
        return 'no_accessories';
      }
      
      // 按配件ID和SKU ID排序，确保相同配置生成相同的哈希值
      const sortedAccessories = accessories
        .map(acc => ({
          id: acc.id,
          sku_id: acc.sku_id || 'no_sku'
        }))
        .sort((a, b) => {
          if (a.id !== b.id) return a.id - b.id;
          return (a.sku_id || '').localeCompare(b.sku_id || '');
        });
      
      // 生成简单的哈希字符串
      return sortedAccessories
        .map(acc => `${acc.id}:${acc.sku_id}`)
        .join('|');
    },
    
    // 搜索客户
    async searchCustomers(queryString, callback) {
      if (queryString.length < 2) {
        callback([]);
        return;
      }
      
      try {
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }
        
        const response = await searchCustomerByCompany(queryString);
        
        if (response.data && response.data.code) {
          const customers = response.data.msg || [];
          const suggestions = customers.map(customer => ({
            value: customer.Name,
            customer: customer
          }));
          callback(suggestions);
        } else {
          callback([]);
        }
      } catch (error) {
        console.error('搜索客户失败:', error);
        if (checkTokenFromError(error)) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          this.$message.error('搜索客户失败');
        }
        callback([]);
      }
    },
    
    // 选择客户
    handleCustomerSelect(item) {
      this.contractForm.customer_id = item.customer.CustomerId;
      this.companyName = item.customer.Name;
      
      // 自动填充收货人信息
      this.contractForm.recipient_name = item.customer.UserName || '';
      this.contractForm.recipient_tel = item.customer.Tel || '';
      this.contractForm.recipient_address = item.customer.Address || '';
      
      // 自动更新所有已选产品的发货信息
      this.cartItems.forEach(cartItem => {
        cartItem.shipping_info.recipient_name = this.contractForm.recipient_name;
        cartItem.shipping_info.recipient_tel = this.contractForm.recipient_tel;
        cartItem.shipping_info.recipient_address = this.contractForm.recipient_address;
      });
      
      // 不自动显示收货人信息区域，让用户手动点击显示
      this.isEditingRecipient = false;
    },
    
    // 切换收货人信息显示/隐藏
    toggleRecipientInfo() {
      this.showRecipientInfo = !this.showRecipientInfo;
    },
    
    // 编辑收货人信息
    editRecipientInfo() {
      this.isEditingRecipient = !this.isEditingRecipient;
    },

    // 处理收货人信息输入变化
    handleRecipientChange() {
      if (this.syncToAllProducts) {
        this.cartItems.forEach(item => {
          item.shipping_info.recipient_name = this.contractForm.recipient_name;
          item.shipping_info.recipient_tel = this.contractForm.recipient_tel;
          item.shipping_info.recipient_address = this.contractForm.recipient_address;
        });
        this.$message.success('收货人信息已同步更新到所有已选产品');
      }
    },

    // 应用收货人信息到所有已选产品
    applyRecipientToAll() {
      this.cartItems.forEach(item => {
        item.shipping_info.recipient_name = this.contractForm.recipient_name;
        item.shipping_info.recipient_tel = this.contractForm.recipient_tel;
        item.shipping_info.recipient_address = this.contractForm.recipient_address;
      });
      this.$message.success('收货人信息已同步更新到所有已选产品');
    },
    
    // 文件选择改变
    async handleFileChange(file, fileList) {
      console.log('文件对象:', file);
      console.log('文件对象详细信息:', {
        name: file.name,
        size: file.size,
        type: file.type,
        raw: file.raw,
        hasRaw: !!file.raw,
        rawType: file.raw ? typeof file.raw : 'undefined'
      });
      
      // 检查文件对象是否有效
      if (!file || !file.raw) {
        this.$message.error('文件对象无效');
        return;
      }
      
      // 限制文件大小
      const isLt2M = file.size / 1024 / 1024 < 100;
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 100MB!');
        // 移除当前文件
        const index = fileList.findIndex(item => item.uid === file.uid);
        if (index > -1) {
          fileList.splice(index, 1);
        }
        this.fileList = fileList;
        return;
      }
      
      // 限制文件类型 - 添加安全检查
      if (file.type && typeof file.type === 'string') {
        const isImage = file.type.startsWith('image/');
        if (!isImage) {
          this.$message.error('只能上传图片文件!');
          // 移除当前文件
          const index = fileList.findIndex(item => item.uid === file.uid);
          if (index > -1) {
            fileList.splice(index, 1);
          }
          this.fileList = fileList;
          return;
        }
      } else {
        // 如果无法获取文件类型，通过文件扩展名检查
        const fileName = file.name || '';
        const validExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'];
        const hasValidExtension = validExtensions.some(ext => 
          fileName.toLowerCase().endsWith(ext)
        );
        
        if (!hasValidExtension) {
          this.$message.error('只能上传图片文件!');
          // 移除当前文件
          const index = fileList.findIndex(item => item.uid === file.uid);
          if (index > -1) {
            fileList.splice(index, 1);
          }
          this.fileList = fileList;
          return;
        }
      }
      
      // 上传图片到服务器
      const imageUrl = await this.uploadSingleImage(file.raw, 'productcontract');
      if (imageUrl) {
        // 上传成功，添加到路径数组
        this.imgUrls.push(imageUrl);
        console.log('合同图片上传成功:', imageUrl);
        console.log('合同图片路径数组:', this.imgUrls);
        
        // 更新文件对象的url属性，以便删除时能正确识别
        const fileIndex = fileList.findIndex(item => item.uid === file.uid);
        if (fileIndex > -1) {
          fileList[fileIndex].url = imageUrl;
        }
      } else {
        // 上传失败，移除文件
        const index = fileList.findIndex(item => item.uid === file.uid);
        if (index > -1) {
          fileList.splice(index, 1);
        }
      }
      
      this.fileList = fileList;
      console.log('文件列表更新:', this.fileList);
    },
    
    // 文件移除
    handleFileRemove(file, fileList) {
      this.fileList = fileList;
      
      // 从路径数组中移除对应的路径
      if (file.url) {
        const index = this.imgUrls.findIndex(url => url === file.url);
        if (index > -1) {
          this.imgUrls.splice(index, 1);
          console.log('从合同图片数组中移除:', file.url);
          console.log('剩余合同图片数组:', this.imgUrls);
        }
      }
    },
    
    // 付款凭证文件选择改变
    async handlePaymentFileChange(file, fileList) {
      console.log('付款凭证文件对象:', file);
      console.log('付款凭证文件对象详细信息:', {
        name: file.name,
        size: file.size,
        type: file.type,
        raw: file.raw,
        hasRaw: !!file.raw,
        rawType: file.raw ? typeof file.raw : 'undefined'
      });
      
      // 检查文件对象是否有效
      if (!file || !file.raw) {
        this.$message.error('文件对象无效');
        return;
      }
      
      // 限制文件大小
      const isLt2M = file.size / 1024 / 1024 < 100;
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 100MB!');
        // 移除当前文件
        const index = fileList.findIndex(item => item.uid === file.uid);
        if (index > -1) {
          fileList.splice(index, 1);
        }
        this.paymentFileList = fileList;
        return;
      }
      
      // 限制文件类型 - 添加安全检查
      if (file.type && typeof file.type === 'string') {
        const isImage = file.type.startsWith('image/');
        if (!isImage) {
          this.$message.error('只能上传图片文件!');
          // 移除当前文件
          const index = fileList.findIndex(item => item.uid === file.uid);
          if (index > -1) {
            fileList.splice(index, 1);
          }
          this.paymentFileList = fileList;
          return;
        }
      } else {
        // 如果无法获取文件类型，通过文件扩展名检查
        const fileName = file.name || '';
        const validExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'];
        const hasValidExtension = validExtensions.some(ext => 
          fileName.toLowerCase().endsWith(ext)
        );
        
        if (!hasValidExtension) {
          this.$message.error('只能上传图片文件!');
          // 移除当前文件
          const index = fileList.findIndex(item => item.uid === file.uid);
          if (index > -1) {
            fileList.splice(index, 1);
          }
          this.paymentFileList = fileList;
          return;
        }
      }
      
      // 上传图片到服务器
      const imageUrl = await this.uploadSingleImage(file.raw, 'productcontract');
      if (imageUrl) {
        // 上传成功，添加到路径数组
        this.paymentImgUrls.push(imageUrl);
        console.log('付款凭证图片上传成功:', imageUrl);
        console.log('付款凭证图片路径数组:', this.paymentImgUrls);
        
        // 更新文件对象的url属性，以便删除时能正确识别
        const fileIndex = fileList.findIndex(item => item.uid === file.uid);
        if (fileIndex > -1) {
          fileList[fileIndex].url = imageUrl;
        }
      } else {
        // 上传失败，移除文件
        const index = fileList.findIndex(item => item.uid === file.uid);
        if (index > -1) {
          fileList.splice(index, 1);
        }
      }
      
      this.paymentFileList = fileList;
      console.log('付款凭证文件列表更新:', this.paymentFileList);
    },
    
    // 付款凭证文件移除
    handlePaymentFileRemove(file, fileList) {
      this.paymentFileList = fileList;
      
      // 从路径数组中移除对应的路径
      if (file.url) {
        const index = this.paymentImgUrls.findIndex(url => url === file.url);
        if (index > -1) {
          this.paymentImgUrls.splice(index, 1);
          console.log('从付款凭证图片数组中移除:', file.url);
          console.log('剩余付款凭证图片数组:', this.paymentImgUrls);
        }
      }
    },
    
    // 单图片上传方法
    async uploadSingleImage(file, type = 'productcontract') {
      try {
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return null;
        }
        
        const token = localStorage.getItem('token');
        const formData = new FormData();
        formData.append('img', file);
        formData.append('type', type);
        formData.append('token', token);
        
        const response = await request({
          method: 'POST',
          data: formData,
          url: 'index.php/api/newfile.Contract/uploadImg',
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        
        if (response.data && response.data.status === 'ok') {
          return response.data.data; // 返回图片URL
        } else {
          this.$message.error(response.data.data || '图片上传失败');
          return null;
        }
      } catch (error) {
        console.error('图片上传失败:', error);
        if (checkTokenFromError(error)) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          this.$message.error('图片上传失败');
        }
        return null;
      }
    },
    
    // 提交表单
    async submitForm() {
      try {
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }
        
        // 检查是否选择了客户
        if (!this.contractForm.customer_id) {
          this.$message.error('请选择客户');
          return;
        }
        
        // 验证表单
        const valid = await this.$refs.contractForm.validate();
        if (!valid) {
          return;
        }
        
        // 检查付款时间（如果付款状态为已付款或部分付款，则付款时间为必填）
        if ((this.contractForm.payment_status === 1 || this.contractForm.payment_status === 2) && !this.contractForm.payment_time) {
          this.$message.error('已付款或部分付款状态下，付款时间为必填项');
          return;
        }
        
        // 检查是否选择了产品
        if (this.cartItems.length === 0) {
          this.$message.warning('请至少选择一个产品生成订单');
          return;
        }
        
        this.submitLoading = true;
        
        // 准备提交数据
        const submitData = { ...this.contractForm };
        
        // 添加图片路径（如果上传了的话）
        if (this.imgUrls.length > 0) {
          console.log('合同图片路径数组:', this.imgUrls);
          submitData.img = this.imgUrls;
        }
        
        // 添加付款凭证图片路径（如果上传了的话）
        if (this.paymentImgUrls.length > 0) {
          console.log('付款凭证图片路径数组:', this.paymentImgUrls);
          submitData.img_payment = this.paymentImgUrls;
        }
        
        // 处理付款时间格式
        if (submitData.payment_time) {
          // 将日期字符串转换为时间戳
          const timestamp = Math.floor(new Date(submitData.payment_time).getTime() / 1000);
          // 检查时间戳是否在合理范围内（1970年到2038年）
          if (timestamp > 0 && timestamp < 2147483647) {
            submitData.payment_time = timestamp;
          } else {
            this.$message.error('付款时间超出有效范围');
            return;
          }
        } else {
          // 如果没有付款时间，设置为null
          submitData.payment_time = null;
        }
        
        // 处理金额格式
        if (submitData.cost) {
          submitData.cost = parseFloat(submitData.cost);
        }
        
        // 处理付款状态
        if (submitData.payment_status !== '') {
          submitData.payment_status = parseInt(submitData.payment_status);
        } else {
          submitData.payment_status = 1; // 默认为1
        }
        
        // 处理施工状态
        if (submitData.is_construction !== '') {
          submitData.is_construction = parseInt(submitData.is_construction);
        } else {
          submitData.is_construction = 0; // 默认为0
        }
        
        // 处理预计付款时间格式
        if (submitData.estimated_payment_time) {
          // 将日期字符串转换为时间戳
          const estimatedTimestamp = Math.floor(new Date(submitData.estimated_payment_time).getTime() / 1000);
          // 检查时间戳是否在合理范围内（1970年到2038年）
          if (estimatedTimestamp > 0 && estimatedTimestamp < 2147483647) {
            submitData.estimated_payment_time = estimatedTimestamp;
          } else {
            this.$message.error('预计付款时间超出有效范围');
            return;
          }
        } else {
          // 如果没有预计付款时间，设置为null
          submitData.estimated_payment_time = null;
        }
        
        // 准备订单数据
        const orderItems = this.cartItems.map(item => ({
          device_id: item.device_id,
          device_name: item.device_name,
          quantity: item.quantity,
          accessories: item.accessories,
          shipping_info: item.shipping_info // 添加发货信息
        }));
        
        // 合并合同和订单数据
        const finalSubmitData = {
          ...submitData,
          order_items: orderItems,
          token:localStorage.getItem('token'),
        };
        
        console.log('准备提交的数据:', finalSubmitData);
        
        // 调用新的接口
        const response = await request({
          method: 'POST',
          data: finalSubmitData,
          url: 'index.php/api/newfile.Contract/addContractProductOrder'
        });
        
        if (response.data && response.data.code) {
          this.$message.success(`合同添加成功，成功生成${response.data.order_count}个订单`);
          this.resetForm();
          // 跳转到合同列表页面
          this.$router.push('/contract-management');
        } else {
          this.$message.error(response.data.msg || '提交失败');
        }
      } catch (error) {
        console.error('提交失败:', error);
        if (checkTokenFromError(error)) {
          // Token无效或过期
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          // 其他错误
          this.$message.error('提交失败');
        }
      } finally {
        this.submitLoading = false;
      }
    },
    
    // 重置表单
    resetForm() {
      this.$refs.contractForm.resetFields();
      this.companyName = '';
      this.fileList = [];
      this.paymentFileList = [];
      this.imgUrls = [];
      this.paymentImgUrls = [];
      this.$refs.upload.clearFiles();
      this.$refs.paymentUpload.clearFiles();
      
      // 重置收货人信息相关状态
      this.showRecipientInfo = false;
      this.isEditingRecipient = false;
      this.contractForm.recipient_name = '';
      this.contractForm.recipient_tel = '';
      this.contractForm.recipient_address = '';
      this.syncToAllProducts = false; // 重置同步选项
      
      // 重置产品选择相关状态
      this.showProductSelection = false;
      this.cartItems = [];
      this.productSearchKeyword = ''; // 重置搜索关键词
      this.filteredDeviceList = this.deviceList; // 重置过滤后的列表
      
      // 重置筛选状态
      this.statusFilter = '';
      this.deviceList = this.originalDeviceList;
      
      // 重新获取合同编号
      this.getContractNumber();
    },
    
    // 返回上一页
    goBack() {
      this.$router.go(-1);
    },

    // 同步发货信息
    async syncShippingInfo() {
      try {
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }

        // 获取当前客户信息
        const customerResponse = await searchCustomerByCompany(this.companyName);
        const customer = customerResponse.data.msg && customerResponse.data.msg.length > 0 ? customerResponse.data.msg[0] : null;

        if (!customer) {
          this.$message.error('未找到客户信息，请先选择客户');
          return;
        }

        // 更新所有已选产品的发货信息
        this.cartItems.forEach(item => {
          item.shipping_info.recipient_name = customer.UserName || '';
          item.shipping_info.recipient_tel = customer.Tel || '';
          item.shipping_info.recipient_address = customer.Address || '';
        });
        this.$message.success('发货信息已同步');
      } catch (error) {
        console.error('同步发货信息失败:', error);
        if (checkTokenFromError(error)) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          this.$message.error('同步发货信息失败');
        }
      }
    },

    // 过滤设备列表
    filterProducts() {
      const keyword = this.productSearchKeyword.toLowerCase();
      this.filteredDeviceList = this.deviceList.filter(device => {
        const deviceNameMatch = device.device_name.toLowerCase().includes(keyword);
        const factoryNameMatch = device.factory.factory_name.toLowerCase().includes(keyword);
        return deviceNameMatch || factoryNameMatch;
      });
    }
  }
}
</script>

<style scoped>
.contract-order-add-view {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 500;
}

.form-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-form {
  padding: 20px 0;
}

/* 收货人信息区域样式 */
.recipient-info-section {
  margin: 20px 0;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background-color: #fafafa;
}

.recipient-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #409eff;
  color: white;
  border-radius: 6px 6px 0 0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.recipient-header:hover {
  background-color: #337ecc;
}

.recipient-title {
  font-size: 16px;
  font-weight: 500;
}

.recipient-toggle {
  font-size: 12px;
  opacity: 0.9;
}

.recipient-content {
  padding: 20px;
}

.recipient-instruction {
  color: #606266;
  margin-bottom: 15px;
  font-size: 14px;
}

.recipient-edit-btn {
  margin-bottom: 20px;
}

.recipient-fields {
  margin-top: 15px;
}

.sync-option {
  display: flex;
  align-items: center;
  margin-top: 15px;
  font-size: 13px;
  color: #606266;
}

.sync-option .el-checkbox {
  margin-right: 10px;
}

.el-upload__tip {
  font-size: 12px;
  color: #606266;
  margin-top: 7px;
}

.el-upload--picture-card {
  width: 148px;
  height: 148px;
  line-height: 146px;
}

.el-upload-list--picture-card .el-upload-list__item {
  width: 148px;
  height: 148px;
}

::v-deep .el-input__inner {
  background-color: white !important;
}

/* 客户搜索选项样式 */
.customer-option {
  padding: 8px 0;
  width: 100%;
}

.customer-option .company-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 6px;
  font-size: 14px;
}

.customer-option .customer-info {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
}

.customer-option .customer-info span {
  display: block;
  margin-bottom: 3px;
}

.customer-option .customer-info span:last-child {
  margin-bottom: 0;
}

/* 调整搜索下拉框宽度 */
:deep(.el-autocomplete-suggestion) {
  min-width: 400px !important;
  max-width: 600px !important;
}

:deep(.el-autocomplete-suggestion__list) {
  max-height: 300px;
  overflow-y: auto;
}

:deep(.el-autocomplete-suggestion__list li) {
  padding: 8px 12px;
  line-height: 1.4;
}

/* 产品选择区域样式 */
.product-selection-section {
  margin-top: 30px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
}

.product-header {
  background-color: #f5f7fa;
  padding: 15px 20px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e4e7ed;
  transition: background-color 0.3s ease;
}

.product-header:hover {
  background-color: #e4e7ed;
}

.product-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.product-toggle {
  font-size: 13px;
  color: #909399;
}

.product-content {
  padding: 20px;
}

.product-instruction {
  color: #606266;
  margin-bottom: 20px;
  font-size: 14px;
  text-align: center;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

/* 产品搜索样式 */
.product-search {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.product-search .el-input {
  width: 100%;
  max-width: 300px;
}

.product-search .el-input__inner {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.product-search .el-input__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.product-search .el-input:hover .el-input__inner {
  border-color: #c0c4cc;
}

/* 设备列表样式 */
.device-list h4 {
  margin: 0 0 15px 0;
  color: #303133;
  border-bottom: 2px solid #67c23a;
  padding-bottom: 8px;
}

.device-item {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 15px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.device-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.device-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.device-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.quantity-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity-selector label {
  font-size: 13px;
  color: #606266;
  white-space: nowrap;
}

.factory-info {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  font-size: 13px;
  color: #606266;
}

.accessories-list h5 {
  margin: 0 0 10px 0;
  color: #606266;
  font-size: 14px;
}

.accessories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 10px;
}

.accessory-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  background-color: #fafafa;
}

.accessory-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.accessory-name {
  font-weight: 500;
  color: #303133;
}

.sku-selection {
  margin-top: 8px;
}

.form-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.form-label {
  font-size: 13px;
  color: #606266;
  min-width: 50px;
}

/* 已选产品样式 */
.selected-products {
  border-top: 2px solid #67c23a;
  padding-top: 20px;
}

.selected-products h4 {
  margin: 0 0 15px 0;
  color: #303133;
  display: flex;
  align-items: center;
}

.empty-cart {
  text-align: center;
  padding: 40px 20px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 2px dashed #dee2e6;
}

.cart-items {
  /* 移除最大高度限制和滚动条 */
  /* max-height: 300px; */
  /* overflow-y: auto; */
}

.cart-item {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 10px;
  background-color: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.cart-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.device-name {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

.device-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.device-config {
  font-size: 12px;
  color: #909399;
  font-weight: normal;
}

.cart-item-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.quantity-section {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity-section label {
  font-size: 13px;
  color: #606266;
  min-width: 50px;
}

.accessories-section {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.accessories-section label {
  font-size: 13px;
  color: #606266;
  min-width: 50px;
  margin-top: 2px;
}

.accessories-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

/* 合同金额输入框样式 */
.amount-input {
  background-color: #fff;
}

.amount-input .el-input__inner {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.amount-input .el-input__inner:focus {
  border-color: #409eff;
  outline: none;
}

.amount-input .el-input-group__prepend {
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-right: none;
  color: #606266;
  font-weight: 500;
}

.amount-input .el-input-group__append {
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-left: none;
}

.amount-input:hover .el-input__inner {
  border-color: #c0c4cc;
}

.amount-input .el-input__inner::placeholder {
  color: #c0c4cc;
}

/* 发货信息区域样式 */
.shipping-info-section {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #dcdfe6;
}

.shipping-title {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #409eff;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 15px;
}

.shipping-title i {
  font-size: 16px;
}

.shipping-form {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.shipping-form .form-item {
  margin-bottom: 15px;
}

.shipping-form .form-label {
  display: block;
  font-size: 13px;
  color: #606266;
  font-weight: 500;
  margin-bottom: 5px;
  white-space: nowrap; /* 防止标签文字换行 */
}

.shipping-form .el-input,
.shipping-form .el-textarea {
  width: 100%;
}

.shipping-form .el-input__inner,
.shipping-form .el-textarea__inner {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.shipping-form .el-input__inner:focus,
.shipping-form .el-textarea__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.shipping-form .el-input:hover .el-input__inner,
.shipping-form .el-textarea:hover .el-textarea__inner {
  border-color: #c0c4cc;
}

/* 同步选项样式 */
.sync-option {
  display: flex;
  align-items: center;
  margin-top: 15px;
  padding: 10px;
  background-color: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 4px;
  font-size: 13px;
  color: #409eff;
}

.sync-option .el-checkbox {
  margin-right: 10px;
}

.sync-option .el-checkbox__label {
  color: #409eff;
  font-weight: 500;
}
</style>

<style>
/* 全局样式：调整搜索下拉框宽度 */
.customer-search-dropdown {
  min-width: 400px !important;
  max-width: 600px !important;
}

.customer-search-dropdown .el-autocomplete-suggestion__list {
  max-height: 300px;
  overflow-y: auto;
}

.customer-search-dropdown .el-autocomplete-suggestion__list li {
  padding: 8px 12px;
  line-height: 1.4;
}
</style> 